import axios, { AxiosRequestConfig } from 'axios';
import router from '@/router/index';

// axios.defaults.withCredentials = true
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 60000, // request timeout
});
const ErrorMsg = '对不起，操作失败';

// 相应拦截器
service.interceptors.response.use(
  (response: any) => {
    const { code, msg } = response.data;
    if (code === 200) {
      return response;
    }
   if (code === 403 || (code === 401 && !response.config.url.includes('/login'))) {
      router.push('/403');
    } 
    
    const error = { code, msg: msg || ErrorMsg };
    console.error('error', error);
    return Promise.reject(error);
  },
  (error: any) => {
    error.msg = error.msg || ErrorMsg;
    console.error('error', error);
    return Promise.reject(error);
  }
);
// Do something with response error
// export default request
// 接口返回数据处理
// export default service
export default <T = any>(config: AxiosRequestConfig) =>
  service(config).then((res) => res.data as T);
